package com.demo.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import com.demo.dao.UserDao;
import com.demo.model.User;
import com.demo.service.UserService;
import com.demo.bean.PageBean;
import com.demo.dao.PageBeanDao;

@Component("userService")
public class UserServiceImpl extends HibernateDaoSupport implements
UserService{
	@Autowired
	private UserDao userDao;
	@Autowired
	private PageBeanDao pageBeanDao;
	
	@Resource(name="sessionFactory")
	public void setSessionFacotry(SessionFactory sessionFacotry) {
		super.setSessionFactory(sessionFacotry);
	}
	@Override
	public void save(User t) {
		userDao.save(t);
	}

	@Override
	public void update(User t) {
		userDao.update(t);
	}

	@Override
	public int delete(String id) {
		return userDao.delete(id);
	}

	@Override
	public User get(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<User> query() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<User> query(String hql) {
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public User getInfoById(Integer id) {
		String sql="select * from SYS_USER where id= ?";
		List<String>params=new ArrayList<String>();
		params.add(id+"");
		User user=userDao.getInfoBySql(sql,params);
		return user;
	}
	@Override
	public PageBean getListByParams(Map<String,Object> params) {
		int pageSize=10;
		int currentpage=1;
		if(params.containsKey("page")) {
			currentpage=(int) params.get("page");
		}
		if(params.containsKey("rows")) {
			pageSize=(int) params.get("rows");
		}
		String sql = "select * from sys_user ";// 查询语句
		int allRow = pageBeanDao.getAllRowCount(sql);// 总记录数
		int totalPage = PageBean.countTotalPage(pageSize, allRow);// 总页数
		int offset = PageBean.countOffset(pageSize, currentpage);// 当前页开始记录
		int length = offset+pageSize;
		if(offset!=0){
			offset=offset+1;
		}
		int currentPage = PageBean.countCurrentPage(pageSize);
		String getSql="select * from sys_user "+
				" limit "+offset+" , "+length;
		List<User> users=userDao.getListBySql(getSql);
		PageBean pageBean = new PageBean();
		pageBean.setPageSize(pageSize);
		pageBean.setCurrentPage(currentPage);
		pageBean.setAllRow(allRow);
		pageBean.setTotalPage(totalPage);
		pageBean.setList(users);
		pageBean.init();
		
		return pageBean;
	}	
}
